var faults = [];
var table;
var undefinedReplace = '空';
var start = $('#startTime').val();
var end = $('#endTime').val();
var stationId = $('#stationId').val();
var columns = [ LocaleTitle.colcums.XuHao, LocaleTitle.colcums.DiaoGuanFanWei, LocaleTitle.colcums.GuZhangShiJian,
		LocaleTitle.colcums.Dianya, LocaleTitle.colcums.GuZhangSheBei, LocaleTitle.colcums.GuZhangLeiXing,
		LocaleTitle.colcums.GuZhangYuanYin, LocaleTitle.colcums.GuZhangXiangBie, LocaleTitle.colcums.GuZhangGuoCheng,
		LocaleTitle.colcums.XingBoCeJu, LocaleTitle.colcums.BeiZhu, LocaleTitle.colcums.XiangXi];
var initColumns = [ LocaleTitle.colcums.XuHao, LocaleTitle.colcums.DiaoGuanFanWei, LocaleTitle.colcums.GuZhangShiJian,
		LocaleTitle.colcums.GuZhangSheBei, LocaleTitle.colcums.GuZhangGuoCheng, LocaleTitle.colcums.XingBoCeJu,
		LocaleTitle.colcums.BeiZhu, LocaleTitle.colcums.XiangXi];
var equipmentsLength = 0;
var voltagesLength = 2;
function init() {
	$('#start').val($('#startTime').val());
	$('#end').val($('#endTime').val());
	$('#stationId').val($('#stationId').val());
	$('#start').datetimepicker({
		format : 'yyyy-mm-dd',
		minView : 2,
		autoclose : true,
		endDate : new Date(),
		todayHighlight : true
	});
	$('#end').datetimepicker({
		format : 'yyyy-mm-dd',
		minView : 2,
		autoclose : true,
		endDate : new Date(),
		pickerPosition : 'bottom-left',
		todayHighlight : true
	});
	loadColumnsFilter(initColumns);
	loadData();
}
function loadData() {
	$.getJSON("/rest/fault/getFaultByStartAndEnd/" + start + "/" + end, function(result) {
		faults = result;
		faults.sort(sortFaults);
		if (stationId == "" || stationId == null || typeof (stationId) == "undefined") {
			loadFilter(stationId);
		} else {
			$('#selectButton').hide();
		}
		var filterFaults = [];
		if (stationId) {
			for ( var i in faults) {
				if (faults[i]['equipment_id'] == stationId) {
					filterFaults.push(faults[i]);
				}
			}
			loadContent(filterFaults);
		} else {
			loadContent(faults);
		}
		stationId = undefined;
	});
}
function sortFaults(obj1, obj2) {
	// 主要按照lastFaultTime排序，次要按照eventStart排序
	var t1 = obj1.faultTime ? obj1.faultTime : 0;
	t1 = t1.time ? t1.time : t1;
	var t2 = obj2.faultTime ? obj2.faultTime : 0;
	t2 = t2.time ? t2.time : t2;
	return t2 - t1;
}
function query() {
	var s = $('#start').val();
	var e = $('#end').val();
	if (s == start && e == end) {
		doFilter();
	} else {
		start = s;
		end = e;
		loadData();
	}
}
function loadFilter(stationId) {
	var equipments = [];
	var equipmentMap = {};
	// time countT maxTime
	for ( var i in faults) {
		var a = faults[i];
		if (stationId && !stationName) {
			if (a['equipment_id'] == stationId) {
				equipment = a.equipment;
			}
		}

		var equipment = a.mapSearchName || a.equipment ? a.mapSearchName || a.equipment : undefinedReplace;
		if (equipments.indexOf(equipment) == -1) {
			equipments.push(equipment);
		}
		// 加title
		var l = equipmentMap[equipment];
		if (!l) {
			l = {
				count : 0
			};
			equipmentMap[equipment] = l;
		}
		l.count++;
	}
	// 先按照count排，count相同按照总时长
	equipments.sort(sortEquipments);
	equipmentsLength = equipments.length;
	$('#equipments').html(getCheckBox(equipments, 'equipments', 'doFilter();', equipmentMap, equipments));
	selectAllVoltages();
	function selectAllVoltages() {
		var ss = document.getElementsByName("voltages");
		var ssAll = document.getElementById("voltagesAll");
		ssAll.checked = true;
		for ( var i in ss) {
			ss[i].checked = true;
		}
	}
	function sortEquipments(equipment1, equipment2) {
		var t1 = equipment1 == undefinedReplace ? 0 : 1;
		var t2 = equipment2 == undefinedReplace ? 0 : 1;
		if (t2 + t1 < 2) {
			return t2 - t1;
		}
		var m1 = equipmentMap[equipment1];
		var m2 = equipmentMap[equipment2];
		return m2.count - m1.count;
	}
}
function loadColumnsFilter(selectColumns) {
	if (!selectColumns) {
		selectColumns = columns;
	}
	$('#columns').html(getCheckBox(columns, 'columns', 'doColumnFilter();', null, selectColumns));
}
function doFilter() {
	var equipments = getCheckBoxValue('equipments');
	var voltages = getCheckBoxValue('voltages');
	changeSelectButtonStatus(equipments, voltages);
	var filterFaults = [];
	for ( var i in faults) {
		var a = faults[i];
		var equipment = a.mapSearchName || a.equipment ? a.mapSearchName || a.equipment : undefinedReplace;
		var voltage = a.voltage ? a.voltage : undefinedReplace;
		if (equipments.indexOf(equipment) > -1 && voltages.indexOf(voltage + "") > -1) {
			filterFaults.push(a);
		}
	}
	loadContent(filterFaults);
}
function changeSelectButtonStatus(equipments, voltages) {
	if (equipments.length == equipmentsLength && voltages.length == voltagesLength) {
		$('#selectButton').removeClass('hasSelected');
	} else {
		$('#selectButton').addClass('hasSelected');
	}
}
function changeColumnsSelectButtonStatus(length) {
	if (columns.length == length) {
		$('#columnsSelectButton').removeClass('hasSelected');
	} else {
		$('#columnsSelectButton').addClass('hasSelected');
	}
}
function getCheckBoxValue(name) {
	var obj = document.getElementsByName(name);
	var s = [];
	for (var i = 0; i < obj.length; i++) {
		if (obj[i].checked) {
			s.push(obj[i].value);
		}
	}
	return s;
}
function getCheckBox(data, name, func, map, selects) {
	var c = '';
	for ( var i in data) {
		if (map) {
			var item = map[data[i]];
			var count = item.count;
			var checked = '';
			if (selects.indexOf(data[i]) > -1) {
				checked = ' checked = "checked" ';
			}
			c += '<label><input name="' + name
					+ '" type="checkbox" onchange="' + func + '" ' + checked + ' value="' + data[i] + '" />' + data[i]
					+ '</label>';
			
		} else {
			var checked = '';
			if (selects.indexOf(data[i]) > -1) {
				checked = ' checked = "checked" ';
			}
			c += '<label><input name="' + name + '" type="checkbox" onchange="' + func + '" ' + checked + ' value="'
					+ data[i] + '" />' + data[i] + '</label>';
		}

	}
	return c;
}
function loadContent(faults) {
	loadTable(faults);
	refreshAllSelectAllButtonStatus();
}
function loadTable(faults) {
	if (table) {
		table.getTable().destroy();
	}
	var opt = MyTable.getDefaultOptions();
	opt.paging = false;
	opt.autoWidth = false;
	var defs = [{targets:0,width:'3%'},
	            {targets:1,width:'7%'},
	            {targets:11,width:'5%'},
	            {targets:2,width:'10%'},
	            {targets:4,width:'8%'},
	            {targets:8,width:'30%'},
	            {targets:9,width:'20%'},
	            {targets:10,width:'20%'},
	];
	opt.scrollY = scrollYHeight + "px";
	var datas = [];
	for ( var i in faults) {
		var f = faults[i];
		var ftime = time(f.faultTime);
		var d = [
					Number(i) + 1,
					str(f.rank),
					ftime,
					str(f.voltage),
					str(f.equipment),
					str(f.faultType),
					str(f.faultReson),
					str(f.faultPhase),
					str(f.description),
					str(f.ranging),
					str(f.remark),
					'<i onclick="gotoFaultDetail(\'' + f['equipment_id'] + '\',\'' + ftime
					+ '\')" class="fa fa-map-o" style="color:red;cursor:pointer;"></i>'];
		datas.push(d);
	}
	// 筛选列
	var eles = document.getElementsByName('columns');
	var targets = [];
	for (var i = 0; i < eles.length; i++) {
		if (!eles[i].checked) {
			targets.push(i);
		}
	}
	defs.push({
		visible : false,
		targets : targets
	});
	opt.columnDefs = defs;
	table = new MyTable("faultTable", columns, opt);
	table.setDataSet(datas).show();
	$('[data-toggle="popover"]').popover();
}
function gotoFaultDetail(lineid, faultTime) {
	var fra = document.createElement("iframe");
	fra.style.background = 'transparent';
	fra.style.border = 0;
	fra.width = "100%";
	fra.id = "faultReportIframe";
	fra.height = (wrapperHeight-10) + "px";
	var s = "/ui/map/protectActSvg/protectActSvg.xhtml?lineId=" + lineid + "&faultTime=" + faultTime
			+ "&showBackButton=" + "true";
	fra.src = s;
	document.body.appendChild(fra);
	$('#contentDiv').css('display', 'none');
};
function backFromFaultReport() {
	document.body.removeChild(document.getElementById("faultReportIframe"));
	$('#contentDiv').css('display', 'block');
	table.getTable().draw();
}
function selectAll(isChecked, name) {
	var eles = document.getElementsByName(name);
	for (var i = 0; i < eles.length; i++) {
		eles[i].checked = isChecked;
	}
	doFilter();
}
function selectAllColumns(isChecked, name) {
	var eles = document.getElementsByName(name);
	for (var i = 0; i < eles.length; i++) {
		eles[i].checked = isChecked;
	}
	doColumnFilter();
}
function doColumnFilter() {
	var eles = document.getElementsByName("columns");
	var length = 0;
	for (var i = 0; i < eles.length; i++) {
		var show = eles[i].checked;
		var col = table.getTable().column(i);
		col.visible(show);
		if (show) {
			length++;
		}
	}
	changeColumnsSelectButtonStatus(length);
	redrawTable();
}
function redrawTable() {
	if (table) {
		table.getTable().draw();
	}
	// $.fn.dataTable.tables( {visible: true, api: true} ).columns.adjust();
}
function str(d) {
	if (d) {
		d += '';
		d = d.replace(/\r\n/g, "<br>");
		d = d.replace(/\n/g, "<br>");
		return d;
	} else {
		return '';
	}
}
function time(v) {
	if (!v) {
		return '';
	} else {
		var t = new Date(v.time ? v.time : v);
		var m = t.getMonth() + 1 > 9 ? (t.getMonth() + 1) : ("0" + (t.getMonth() + 1));
		var d = t.getDate() > 9 ? t.getDate() : "0" + t.getDate();
		var h = t.getHours() > 9 ? t.getHours() : "0" + t.getHours();
		var min = t.getMinutes() > 9 ? t.getMinutes() : "0" + t.getMinutes();
		var s = t.getSeconds() > 9 ? t.getSeconds() : "0" + t.getSeconds();
		var timestr = t.getFullYear() + "-" + m + "-" + d + " " + h + ":" + min + ":" + s;
		return timestr;
	}
}
function refreshAllSelectAllButtonStatus() {
	var ids = [ 'columns', 'equipments', 'voltages' ];
	for ( var i in ids) {
		refreshSelectAllButtonStatus(ids[i]);
	}
}
function refreshSelectAllButtonStatus(id) {
	var eles = document.getElementsByName(id);
	var all = document.getElementById(id + 'All');
	var checked = true;
	for (var i = 0; i < eles.length; i++) {
		var show = eles[i].checked;
		if (!show) {
			checked = false;
			break;
		}
	}
	all.checked = checked;
}

function resizeHtml() {
	if (table) {
		table.getTable().draw();
	}
}
